package com.kotodama.application.cqrs.handlers.tenant;

import com.kotodama.application.cqrs.queries.tenant.GetTenantByIdQuery;
import com.kotodama.application.cqrs.handlers.QueryHandler;
import com.kotodama.domain.entities.Tenant;
import com.kotodama.domain.exceptions.TenantNotFoundException;
import com.kotodama.domain.repositories.TenantRepository;
import com.kotodama.infrastructure.cache.TenantCacheService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 根据ID获取租户查询处理器
 * 集成缓存功能
 */
@Component
public class GetTenantByIdQueryHandler implements QueryHandler<GetTenantByIdQuery, Tenant> {

    private final TenantRepository tenantRepository;
    private final TenantCacheService tenantCacheService;

    public GetTenantByIdQueryHandler(TenantRepository tenantRepository,
            TenantCacheService tenantCacheService) {
        this.tenantRepository = tenantRepository;
        this.tenantCacheService = tenantCacheService;
    }

    @Override
    @Transactional(readOnly = true)
    public Tenant handle(GetTenantByIdQuery query) {
        // 先从缓存查找
        var cachedTenant = tenantCacheService.getTenantById(Long.parseLong(query.getTenantId()));
        if (cachedTenant.isPresent()) {
            return cachedTenant.get();
        }

        // 缓存未命中，从数据库查找
        Tenant tenant = tenantRepository.findById(query.getTenantId())
                .orElseThrow(() -> new TenantNotFoundException(query.getTenantId()));

        // 缓存查询结果
        tenantCacheService.cacheTenantById(tenant);

        return tenant;
    }

    @Override
    public Class<GetTenantByIdQuery> getSupportedQueryType() {
        return GetTenantByIdQuery.class;
    }
}